package cn.uniqueinfo.dp.controller;

import cn.uniqueinfo.dp.exception.UQException;
import cn.uniqueinfo.dp.service.*;
import cn.uniqueinfo.dp.util.BizUtil;
import cn.uniqueinfo.dp.util.DBUtil;
import cn.uniqueinfo.dp.util.PermissionUtil;
import cn.uniqueinfo.dp.util.ResultUtil;
import cn.uniqueinfo.dp.vo.*;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author:朱元勋
 * @mail:395910063@qq.com
 * @date:2019-01-10 16:09:04
 * @description:业务配置,按钮权限，数据权限，列表显示设置
 */
@Slf4j
@Controller
@RequestMapping(value = "/biz")
public class BizController {

    /** 控制器名称对应权限前缀 */
    protected String ctlName = "biz";

    @Autowired private IFormService fService;
    @Autowired private IFormAuthService faService;
    @Autowired private IFormButtonService fbService;
    @Autowired private IFormGridColumnService fgcService;
    @Autowired private IFormGridService fgService;
    @Autowired private IBizService bizService;

    /**
     * @author:朱元勋
     * @date:2019/2/18 09:16
     * @description: 校验是否有业务表单权限
     * @param:formName 业务表单唯一标识
     * @param:permission 权限点
     * @param:type 操作类型方法名称
     * @return:void
     */
    protected void checkPermission(String formName, String permission, String type) {
        log.warn("自定义业务表单权限验证,表单标识=" + formName + ",权限点=" + permission + ",方法名=" + type);
        PermissionUtil.checkPermission(formName, permission);
    }

    /** 自定义表单创建 */
    @GetMapping("/index")
    public ModelAndView index(@RequestParam(value = "fn") String formName) {

        try {
            checkPermission(formName, "index", "index");
            // 获取当前登录人信息
            UserVO user = (UserVO) SecurityUtils.getSubject().getPrincipal();
            // 获取业务表单配置信息
            FormVO formVO = this.fService.findByFormName(formName);
            if (formVO == null) {
                throw new UQException(0, "获取业务表单信息", "无法获取业务表单信息,当前业务标识是" + formName);
            }
            if (formVO.getFormStatus() == 0) {
                throw new UQException(0, "业务表单状态", "当前业务标识为" + formName + "的状态为禁用状态");
            }
            // 获取业务表单对应的按钮配置信息
            List<FormButtonVO> formButtonList = this.fbService.findButtons(formName,user.getRoles());
            // 获取业务表单对应表格内容配置信息
            List<FormGridColumnVO> formGridColumnList = this.fgcService.findGridColumns(formName,user.getRoles());
            HashMap<String, String> param = new HashMap<>();
            param.put("buttons", BizUtil.genButtonInfos(formButtonList));
            param.put("heads", BizUtil.genTableHead(formGridColumnList));
            param.put("fn", formName);
            param.put("tn", formVO.getTableName());
            param.put("url", "page?fn=" + formName);
            return new ModelAndView("/biz/index", param);
        } catch (Exception e) {
            e.printStackTrace();
            throw new UQException(0, "biz", "创建业务表单失败", e);
        }
    }

    /** 操作界面 */
    @GetMapping("/h")
    public ModelAndView handle(@RequestParam(value = "fn") String formName, @RequestParam(value = "tn") String tableName, @RequestParam(value = "fi") Long formId) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("formName", formName);
        params.put("tableName", tableName);
        params.put("formId", formId);
        params.put("item", "");
        if (formId != 0) {
            HashMap item = this.bizService.getItem(tableName, formId);
            params.put("item", item);
        }
        return new ModelAndView("/biz/" + formName + "/handle", params);
    }
    /** 查询界面 */
    @GetMapping("/q")
    public ModelAndView query(@RequestParam(value = "fn") String formName, @RequestParam(value = "tn") String tableName) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("formName", formName);
        params.put("tableName", tableName);
        return new ModelAndView("/biz/" + formName + "/query", params);
    }

    /** 新增或修改 */
    @PostMapping("/ae")
    @ResponseBody
    private Result onAddOrEdit(@RequestParam Map<String, Object> params, String formName, Integer id) {
        try {
            if (id == 0) {
                HashMap param = new HashMap();
                param.put("sql", BizUtil.insertSql(params));
                this.bizService.insertItem(param);
            } else {
                HashMap param = new HashMap();
                param.put("sql", BizUtil.updateSql(params));
                this.bizService.updateItem(param);
            }

            return ResultUtil.success();
        } catch (Exception e) {
            e.printStackTrace();
            // throw new UQException(0, "biz save", "保存数据失败");
        }
        return ResultUtil.fail();
    }

    /** 动态获取业务表单数据 */
    @GetMapping("/page")
    @ResponseBody
    public EasyuiTableResult getDatas(@RequestParam(value = "fn") String formName, @RequestParam(value = "q", required = false) String query, Integer page, Integer rows) {
        log.info("formName:" + formName + ",page:" + page + ",rows:" + rows);
        log.warn(query);
        try {
            // 获取当前登录人信息
            UserVO user = (UserVO) SecurityUtils.getSubject().getPrincipal();
            // 获取业务表单配置
            FormGridVO formGrid = this.fgService.findByFormName(formName);
            List<FormGridColumnVO> columnList = this.fgcService.findGridColumns(formName,user.getRoles());
            List<QueryVO> queryList = null;
            if (query != null && query.trim().length() != 0) {
                queryList = JSONObject.parseArray(query, QueryVO.class);
            }
            // 获取业务角色信息
            List<FormAuthVO> formAuthList = this.faService.findAuth(formName,user.getRoles());
            if(formAuthList == null || formAuthList.size() == 0){
                throw new UQException(0,"biz","当前用户["+user.getLoginName()+"]对业务表单["+formName+"]没有数据权限");
            }
            HashMap hashMap = DBUtil.genDynaminSql(formGrid, columnList, queryList, formAuthList, user);
            log.info(JSONObject.toJSONString(hashMap));
            return this.bizService.dynamicSql(hashMap, page, rows);
        } catch (Exception e) {
            e.printStackTrace();
            throw new UQException(0, "biz", "分页查询失败", e);
        }
    }

    /** 删除 */
    @PostMapping(value = "/del")
    @ResponseBody
    public Result deleteItems(@RequestParam(value = "fn") String formName, @RequestParam(value = "tn") String tableName, @RequestParam(value = "ids") String ids) {
        this.bizService.deleteItems(tableName, ids);
        return ResultUtil.success();
    }
}
